'use strict';
import Base from './base.js';
export default class extends Base{

	// 获取收入和支出列表信息
	async getcostlistAction(){
		let page = JSON.parse(this.post('page'));
		let pages = page.pages;
		let limits = page.limits;
		let searchstr = page.searchstr;

		let shopid = this.shop_userinfo.departmentid;
		let where ={
			'ct.typename|cd.name|c.costmoney|c.remarks': ['like', '%'+page.searchstr+'%'],
			'c.shopid': shopid,
		}

		if (page.times && (page.times[0] != null && page.times[1] != null)) {
			let begintime = Math.floor(new Date(page.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date( page.times[1]).setHours(0,0,0,0)/1000) + 86400 // 当天加上一天
			where['c.addtime'] = {'>=': begintime, '<': endtime}
		}
		let glist = await this.model('or_shop_cost')
						.alias('c')
						.field('c.*,ct.typename,cd.name as accountname')
						.join('left join `think_or_shop_costtype` ct on ct.id=c.costtypeid')
						.join('left join `think_or_shop_account` cd on cd.id=c.accountid')
						.where(where)
						.page(pages, limits)
						.order('c.id desc')
						.countSelect()
		return this.json(glist);
	}

	// 新增费用类型分类
	async addtypeAction(){
		let data = this.post();
		let shopid = this.shop_userinfo.departmentid;
		data.shopid = shopid;
		
		let isrepeat = await this.model().query('select typename from `think_or_shop_costtype` where shopid='+shopid+' and typename="'+data.typename+'"');
		if (!think.isEmpty(isrepeat)) {
			return this.fail('费用分类重复');
		}
		let res = await this.model('or_shop_costtype').add(data);
		return res?this.success({info:'添加成功'}):this.fail('添加失败');
	}

	// 获取费用类型分类列表
	async getcosttypeAction(){
		let data = await this.model('or_shop_costtype').where({shopid:this.shop_userinfo.departmentid}).select();
		return this.json(data);
	}

	// 删除无用的类型分类名称
	async deltypeAction(){
		let delarr = JSON.parse(this.post('del'));
		let isE;
		for(var j = 0, delen = delarr.length; j < delen; j++){
			isE = await this.model('or_shop_cost').where({costtypeid:delarr[j]}).select();
			if (!think.isEmpty(isE)) {
				return this.fail('分类已使用，不能删除');
			}
		}
		let res = await this.model('or_shop_costtype').where({id:['IN',delarr]}).delete();
		return res?this.success({info:'删除成功'}):this.fail('删除失败');
	}

	// 添加收支信息
	async addcostAction(){
		let shopid = this.shop_userinfo.departmentid;

		if (this.isGet) {
			let type = this.get('type');
			let category = await this.model('or_shop_costtype').where({shopid: shopid,type:type}).select();
			let account = await this.model('or_shop_account').where({departmentid: shopid, isdisable: 0}).select();
			let data = {
				cate : category,
				acco : account,
			}
			return this.json(data);
		}

		let data = this.post();
		let addtime = Math.round(new Date().valueOf()/1000);
		data.shopid = shopid;
		data.addtime = addtime;
		data.fydate = Math.round(new Date(data.fydate).valueOf()/1000);
		let model = this.model('or_shop_cost');
		await model.transaction(async () => {
			try {
				// 添加费用信息获取添加ID
				let costid = await model.add(data);
				// 添加费用金额
				let addaccount = 0;
				if (data.type&2) {
					addaccount = await this.model('or_shop_account').db(model.db()).where({id:data.accountid}).decrement('balance',-(-data.costmoney));
				} else {
					addaccount = await this.model('or_shop_account').db(model.db()).where({id:data.accountid}).increment('balance',-(-data.costmoney));
				}

				// 制作添加金额日志表
				let addaccountlog = {
					departmentid : data.shopid,
					accountid : data.accountid,
					ordertype : data.type==1?'SRD':'ZCD',
					type : data.type,
					orderid : costid,
					money : data.type == 1 ? data.costmoney : -1 * data.costmoney,
					addtime : addtime,
				}
				// 添加收款日志
				let addaccolog = await this.model('or_shop_accountlog').db(model.db()).add(addaccountlog);
				if (costid && addaccount && addaccolog) {
					model.commit();
					return this.success({info:"添加成功"});
				} else {
					model.rollback();
					return this.fail('添加失败');
				}
			} catch(e) {
				model.rollback();
				return this.fail('添加失败');
			}
		})
	}

	// 删除当前费用信息
	async deletecostinfoAction(){
		let id = this.post('id');

		let type = this.post('type')==1?'SRD':'ZCD';

		let shopid = this.shop_userinfo.departmentid;

		let model = this.model('or_shop_cost');

		await model.transaction(async () => {
			try {

				// 获取收款日志
				let accountlog = await this.model('or_shop_accountlog').db(model.db()).where({departmentid: shopid, ordertype: type, orderid: id}).find();

				// 还原收款金额
				let restore = 0;
				if (type&2) {
					restore = await this.model('or_shop_account').db(model.db()).where({id:accountlog.accountid}).increment('balance',accountlog.money);
				} else {
					restore = await this.model('or_shop_account').db(model.db()).where({id:accountlog.accountid}).decrement('balance',accountlog.money);
				}

				// 删除收款日志信息
				let delelog = await this.model('or_shop_accountlog').db(model.db()).where({departmentid: shopid, ordertype: type, orderid: id}).delete();

				// 判断当前费用单，如果是工资支出单，则删除对应的发放工资信息
				let cunzai = await this.model('or_shop_usergongzi').db(model.db()).where({shopid: shopid, orderid: id}).find();

				if (!think.isEmpty(cunzai)) {
					let delcunzai = await this.model('or_shop_usergongzi').db(model.db()).where({shopid: shopid, orderid: id}).delete();
					if (!delcunzai) {
						await model.rollback();
						return this.fail('删除工资单失败');
					}
				}

				// 删除费用信息
				let delcost = await model.where({id: id}).delete();

				if (restore && delelog && delcost) {
					model.commit();
					this.success('删除成功');
				} else {
					model.rollback();
					this.fail('删除失败');
				}
			} catch(e) {
				model.rollback();
				this.fail('删除失败');
			}
		})
	}

}